<template>
  <PageWrapper title="商品分类" contentFullHeight>
    <BasicTable @register="register" :data-source="state.categoryList">
      <template #toolbar>
        <a-button type="primary" @click="handleAddCategory">添加分类</a-button>
      </template>
      <template #cat_deleted="{ record }">
        <CheckCircleTwoTone twoToneColor="#52c41a" v-if="!record.cat_deleted" />
        <CloseCircleTwoTone twoToneColor="#f5222d" v-else />
      </template>
      <template #cat_level="{ record }">
        <a-tag v-if="record.cat_level == 0" color="rgba(0, 132, 244)">一级</a-tag>
        <a-tag v-if="record.cat_level == 1" color="rgba(0, 150, 136)">二级</a-tag>
        <a-tag v-if="record.cat_level == 2" color="rgba(255, 152, 0)">三级</a-tag>
      </template>
      <template #operations="{ record }">
        <TableAction
          stopButtonPropagation
          :actions="[
            {
              label: '编辑',
              icon: 'ant-design:edit-outlined',
              onClick: handleEdit.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '删除',
              icon: 'ic:outline-delete-outline',
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
              popConfirm: {
                title: '是否删除？',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <editModal
      :editStatus="state.editStatus"
      :editRow="state.editRow"
      @register="modalRegister"
      @add-result="addResult"
      @edit-result="editResult"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, toRaw, watch } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useShopGoodsStore } from '/@/store/modules/shopGoodsStore';
  import { CheckCircleTwoTone, CloseCircleTwoTone } from '@ant-design/icons-vue';
  import editModal from './components/editModal.vue';
  import { useModal } from '/@/components/Modal';
  import { message } from 'ant-design-vue';
  import { depthFirstSearch } from '/@/utils/common';

  type stateModel = {
    categoryList: object[] | any;
    editStatus: boolean;
    editRow: object;
  };

  const [modalRegister, { openModal, getVisible }] = useModal();

  const shopGoodsStore = useShopGoodsStore();

  const state: stateModel = reactive({
    categoryList: [],
    editStatus: false,
    editRow: {},
  });

  const getCategories = async () => {
    try {
      const data = await shopGoodsStore.getCategoryList({ resultType: 'list' });
      state.categoryList = data;
    } catch (error) {
      console.log(error);
    }
  };

  const handleAddCategory = async () => {
    try {
      await shopGoodsStore.getCategoryList({ resultType: 'tree', type: 2 });
      openModal();
    } catch (error) {
      console.error(error);
    }
  };

  const addResult = (data: any) => {
    if (data.cat_level == 0) {
      state.categoryList.push(data);
    } else {
      depthFirstSearch(state.categoryList, (item) => {
        if (item.cat_id == data.cat_pid) {
          item.children ? item.children.push(data) : (item['children'] = [data]);
        }
      });
    }
  };

  const editResult = (data: any) => {
    depthFirstSearch(state.categoryList, (item) => {
      if (item.cat_id == data.cat_id) {
        item.cat_name = data.cat_name;
      }
    });
  };

  const handleEdit = async (record: any) => {
    try {
      await shopGoodsStore.getCategoryList({ resultType: 'tree', type: 2 });
      state.editStatus = true;
      const { cat_id } = record;
      const rowData = {
        cat_id,
        cat_name: '',
        firstLevel: null,
        secondLevel: null,
      };
      depthFirstSearch(toRaw(state.categoryList), (item) => {
        if (item.cat_id == record.cat_id) {
          rowData.cat_name = item.cat_name;
          if (item.cat_level == 2) {
            rowData.secondLevel = item.cat_pid;
          }
          if (item.cat_level == 1) {
            rowData.firstLevel = item.cat_pid;
          }
        }
        if (item.cat_id == rowData.secondLevel) {
          rowData.firstLevel = item.cat_pid;
        }
      });
      state.editRow = rowData;
      openModal();
    } catch (error) {
      console.error(error);
    }
  };

  const handleDelete = async (record: any) => {
    try {
      await shopGoodsStore.deleteCategory({ id: record.cat_id });
      const deleteFilter = (data: object[]) => {
        const newData = data.filter((item: any) => item.cat_id != record.cat_id);
        newData.forEach(
          (item: any) => item.children && (item.children = deleteFilter(item.children)),
        );
        return newData;
      };
      state.categoryList = deleteFilter(state.categoryList);
      message.success('删除成功');
    } catch (error) {
      console.error(error);
    }
  };

  onMounted(() => {
    getCategories();
  });

  watch(
    () => getVisible?.value,
    (visible) => {
      if (!visible) {
        state.editStatus = false;
      }
    },
  );

  const [register] = useTable({
    rowKey: (record: any) => {
      return record.cat_id;
    },
    columns: [
      {
        title: '分类名称',
        align: 'left',
        dataIndex: 'cat_name',
      },
      {
        title: '是否有效',
        align: 'left',
        dataIndex: 'cat_deleted',
        slots: { customRender: 'cat_deleted' },
      },
      {
        title: '分类级别',
        align: 'left',
        dataIndex: 'cat_level',
        slots: { customRender: 'cat_level' },
      },
    ],
    striped: true,
    bordered: true,
    showTableSetting: false,
    // expandRowByClick: true,
    isTreeTable: true,
    actionColumn: {
      title: '操作',
      align: 'left',
      dataIndex: 'operations',
      slots: { customRender: 'operations' },
    },
  });
</script>
